package net.cn_su.sharpeyes.activity;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;

import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

import net.cn_su.sharpeyes.R;
import net.cn_su.sharpeyes.adapter.MessageAdapter;
import net.cn_su.sharpeyes.beans.MessageInfo;
import net.cn_su.sharpeyes.pref.ServerInfo_;
import net.cn_su.sharpeyes.utils.UIUtil;
import net.cn_su.sharpeyes.utils.http.HttpClient;
import net.cn_su.sharpeyes.utils.http.HttpUrl;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.Fullscreen;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.annotate.JsonAutoDetect;
import org.codehaus.jackson.annotate.JsonMethod;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;

import java.io.IOException;
import java.util.List;

import cz.msebera.android.httpclient.Header;
import in.srain.cube.views.ptr.loadmore.LoadMoreContainer;
import in.srain.cube.views.ptr.loadmore.LoadMoreHandler;
import in.srain.cube.views.ptr.loadmore.LoadMoreListViewContainer;

/**
 * 政务通知
 */
@EActivity(R.layout.activity_zenwu_list)
@Fullscreen
public class MessageListActivity extends AppCompatActivity {


    @ViewById(R.id.load_more_list_view_container)
    protected LoadMoreListViewContainer loadMoreListViewContainer;
    @ViewById(R.id.lv_data)
    protected ListView mLvData;


    @ViewById
    protected ProgressBar progressBar;
    /**
     * 上拉加载是否完成
     */
    private boolean isLoadMoreFinish = true;

    private int p = 0;
    /**
     * 每页的条数
     */
    private final String COUNT = "20";

    @Extra
    int orgId;

    private MessageAdapter mAdapter;
    @Pref
    ServerInfo_ mServerInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    @AfterViews
    protected void initData() {


        loadMoreListViewContainer.useDefaultFooter();
        loadMoreListViewContainer.setAutoLoadMore(false);
        loadMoreListViewContainer.loadMoreFinish(false, true);

        loadMoreListViewContainer.setLoadMoreHandler(new LoadMoreHandler() {
            @Override
            public void onLoadMore(final LoadMoreContainer loadMoreContainer) {

                onLoadingRefreshing();


            }
        });


        mLvData.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                MessageDetailActivity_.intent(MessageListActivity.this)
                        .extra("info", mAdapter.findAll().get(position))
                        .start();
            }
        });


        doHttp();
    }

    private void doHttp() {

        RequestParams params = new RequestParams();
        params.add("page", "0");
        params.add("count", COUNT);
        params.add("org_id", orgId+"");
        params.add("user_id", mServerInfo.userId().get().toString());
        HttpClient.get(HttpUrl.ARTICLES, params, new TextHttpResponseHandler() {
            @Override
            public void onStart() {
                super.onStart();
                showProgressBar();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                hideProgressBar();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {


            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
     //           Logger.json(responseString);
                ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, JsonAutoDetect.Visibility.ANY);
                mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
                try {
                    JsonNode jsonNode = mapper.readTree(responseString);

                    List<MessageInfo> mList = mapper.readValue(jsonNode.get("list"), new TypeReference<List<MessageInfo>>() {
                    });

                    if (mAdapter == null) {
                        mAdapter = new MessageAdapter(MessageListActivity.this, mList, R.layout.item_zhenwu);
                        mLvData.setAdapter(mAdapter);
                    } else {
                        mAdapter.removeAll();
                        mAdapter.addAll(mList);
                    }
                    if (mList.size() > 0) {
                        loadMoreListViewContainer.loadMoreFinish(false, true);
                    } else {
                        loadMoreListViewContainer.loadMoreFinish(false, false);
                    }
                    p++;
                } catch (IOException e) {
                    e.printStackTrace();
                }


            }


        });
    }


    public void onLoadingRefreshing() {

        if (isLoadMoreFinish) {
            isLoadMoreFinish = false;
            RequestParams params = new RequestParams();
            params.add("page", p + "");
            params.add("count", COUNT);
            params.add("org_id", orgId+"");
            params.add("user_id", mServerInfo.userId().get().toString());
            HttpClient.get(HttpUrl.ARTICLES, params, new TextHttpResponseHandler() {
                @Override
                public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                    isLoadMoreFinish = true;
                }

                @Override
                public void onFinish() {
                    super.onFinish();

                }

                @Override
                public void onSuccess(int statusCode, Header[] headers, String responseString) {
                    isLoadMoreFinish = true;

                //    Logger.v(responseString);
                    ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, JsonAutoDetect.Visibility.ANY);
                    mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
                    try {
                        JsonNode jsonNode = mapper.readTree(responseString);
                        List<MessageInfo> mList = mapper.readValue(jsonNode.get("list"), new TypeReference<List<MessageInfo>>() {
                        });
                        p++;
                        if (mAdapter != null && mList.size() > 0) {
                            mAdapter.addAll(mList);
                            loadMoreListViewContainer.loadMoreFinish(false, true);
                        } else {
                            UIUtil.showToast(MessageListActivity.this, "没有更多了");
                            loadMoreListViewContainer.loadMoreFinish(false, false);
                        }

                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }

            });
        }
    }


    /**
     * 返回
     */
    @Click(R.id.btn_back)
    protected void btnFinish() {
        finish();
    }


    /**
     * 隐藏进度条
     */
    @UiThread
    protected void hideProgressBar() {
        progressBar.setVisibility(View.GONE);
    }

    /**
     * 显示进度条
     */
    @UiThread
    protected void showProgressBar() {
        progressBar.setVisibility(View.VISIBLE);
    }
}
